import {Injectable} from '@nestjs/common';
// ORM
import {InjectRepository} from '@nestjs/typeorm';
import {Repository, UpdateResult} from 'typeorm';
import {ApplyDeviceEntity} from '../entity/apply.device.entity';
import {ApplyDeviceDto} from '../dto/apply.device.dto';
import {ApplyDeviceStatus} from "../common/constants";

@Injectable()
export class ApplyDeviceService {
    constructor(
        @InjectRepository(ApplyDeviceEntity)
        private readonly applyDeviceRepository: Repository<ApplyDeviceEntity>,
    ) {
    }

    async createOne(applyDeviceDto: ApplyDeviceDto): Promise<ApplyDeviceEntity> {
        return await this.applyDeviceRepository.save(applyDeviceDto);
    }

    async editOne(applyDeviceDto: ApplyDeviceDto): Promise<UpdateResult> {
        return await this.applyDeviceRepository.update({deviceSn: applyDeviceDto.deviceSn}, applyDeviceDto);
    }

    async getOneBySn(deviceSn: string): Promise<ApplyDeviceEntity> {
        const qb = this.applyDeviceRepository.createQueryBuilder();
        qb.where({deviceSn})
        return qb.getOne()
    }

    async getAll(status?: ApplyDeviceStatus): Promise<ApplyDeviceEntity[]> {
        const qb = this.applyDeviceRepository.createQueryBuilder();
        if (status) {
            qb.where({status})
        }
        return qb.getMany()
    }
}
